// /* eslint-disable indent */
import React, { useState, useRef, useEffect } from 'react';

import { useDispatch } from 'react-redux';

import TyTimePicker from '@ray-js/components-ty-time-picker';
import { View, Button, Text, router, hideMenuButton, showLoading, hideLoading } from '@ray-js/ray';
import { Dialog, NavBar, Tabs, Tab, ConfigProvider } from '@ray-js/smart-ui';
import { updateTimerList } from '@/redux/modules/scheduleStateSlice';
import { useSystemInfo } from '@/hooks/useSystemInfo';
import _ from 'lodash';
import Strings from '../i18n';
import Weeks from '../component/weeks';
import Note from '../component/note';
import Action from '../component/action';
import Picker from '../component/picker';
import Calendar from '../component/calendar';

import { addSchedule, updateSchedule, removeSchedule } from '../utils';
import { AddOrEditParams, TimerModel } from '../type';

import styles from './index.module.less';

const height = '40';

const pickerBorderBg = '#ccc';

export default function AddSchedule({ location }) {
  const { is24Hour: is24H } = useSystemInfo();

  const { query } = location;

  const isEdit = query?.isEdit === 'true';

  const currentInfo = JSON.parse(query?.currentInfo || '{}') as TimerModel;

  const { timerId, time: originTime, loops, aliasName, dps: originDps } = currentInfo;

  const getTime = () => {
    const now = new Date();
    const hour = now.getHours();
    const minute = now.getMinutes();
    if (isEdit) {
      const [hour, minute] = originTime.split(':');
      return {
        hour: +hour,
        minute: +minute,
      };
    }
    return {
      hour,
      minute,
    };
  };

  const getWeeks = () => {
    if (isEdit) {
      return loops.split('').map(Number);
    }
    return [0, 0, 0, 0, 0, 0, 0];
  };

  const getNote = () => {
    if (isEdit) {
      return aliasName;
    }
    return '';
  };

  const getDps = () => {
    if (isEdit) {
      return originDps;
    }
    return {
      1: false,
    };
  };

  const [weeks, setWeeks] = useState<number[]>(getWeeks);
  const [note, setNote] = useState<string>(getNote);
  const [time, setTime] = useState(getTime);
  const [dps, setDps] = useState<Record<string, any>>(getDps);

  const [curDayDate, setCurDayDate] = useState<any>(new Date(2024, 0, 15).getTime());

  const dispatch = useDispatch();

  const handlePickerChange = (value: { hour: number; minute: number }) => {
    setTime(value);
  };

  const handleWeeksChange = (value: any) => {
    setWeeks(value);
  };

  const handleNoteChange = (value: string) => {
    setNote(value);
  };

  const handleActionChange = (value: Record<string, any>) => {
    setDps(value);
  };

  useEffect(() => {
    hideMenuButton();
  }, []);

  const handleSave = async () => {
    const Api = isEdit ? updateSchedule : addSchedule;

    const { hour, minute } = time;

    const timeStr = `${_.padStart(`${hour}`, 2, '0')}:${_.padStart(`${minute}`, 2, '0')}`;

    const params: AddOrEditParams = {
      time: timeStr,
      loops: weeks.join(''),
      aliasName: note,
      dps,
    };

    if (isEdit) {
      params.timerId = timerId;
    }
    showLoading();
    Api(params).then(res => {
      hideLoading();
      dispatch(updateTimerList(res));
      router.back();
    });
  };

  const onClickLeft = React.useCallback(event => {
    router.back();
  }, []);

  const handleDelete = () => {
    if (!isEdit) return;
    removeSchedule(timerId).then(res => {
      dispatch(updateTimerList(res));
      router.back();
    });
  };

  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <NavBar
        title="Home"
        leftArrow
        onClickLeft={onClickLeft}
        rightText={isEdit ? Strings.getLang('delete') : ' '}
        onClickRight={handleDelete}
        rightTextClass={styles.deleteStyle}
      />
      <Picker time={time} handlePickerChange={handlePickerChange} />

      {/* <ConfigProvider > */}
      <Tabs type="card" animated className={styles.tabsNav}>
        <Tab title="标签 1">
          <Weeks style={{ marginTop: 32 }} weeks={weeks} onChange={handleWeeksChange} />
        </Tab>
        <Tab title="标签 2">
          <Calendar curDayDate={curDayDate} setCurDayDate={setCurDayDate} />
        </Tab>
      </Tabs>
      {/* </ConfigProvider> */}
      <Note style={{ marginTop: 32 }} note={note} onChange={handleNoteChange} />
      <Action style={{ marginTop: 32 }} dps={dps} dpId="1" onChange={handleActionChange} />
      <Button>
        <Text onClick={handleSave}> {Strings.getLang('save')} </Text>
      </Button>
      <Dialog id="smart-dialog" />
    </View>
  );
}
